package com.zrrd.yunchmall;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zrrd.yunchmall.entity.Student;


import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.ArrayList;

/**
 * @author yekong
 */
@SpringBootTest
@RunWith(SpringRunner.class)
@SuppressWarnings("all")
public class EsTest1 {
    @Autowired
    private RestHighLevelClient esClient;

    //学习使用ES的Java API来完成ES的访问
    //常见的http访问方式是：GET（查询），PUT（），POST（），DELETE（删除）
    //1、创建一个Es索引
    @Test
    public void t1() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("index_shz");
        CreateIndexResponse response = esClient.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
    }

    //2、查询索引有没有创建成功（索引是否存在）
    @Test
    public void t2() throws IOException {
        //创建一个查询索引的请求
        GetIndexRequest request = new GetIndexRequest("index_shz");
        //判断索引是否存在
        boolean isExist = esClient.indices().exists(request, RequestOptions.DEFAULT);
        //输出结果
        System.out.println("索引index_shz是否存在： " + isExist);
    }

    @Test
    public void t11() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("index_text5");
        CreateIndexResponse response = esClient.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
    }

    //3、删除索引
    @Test
    public void t3() throws IOException {
        //创建一个删除索引
        DeleteIndexRequest request = new DeleteIndexRequest("index_text5");
        //通过调用ES客户端删除指定的索引
        AcknowledgedResponse response = esClient.indices().delete(request, RequestOptions.DEFAULT);
        //输出结果
        System.out.println(response.isAcknowledged());
    }

    //4、创建索引文档
    @Test
    public void t4() throws IOException {
        //创建一个对象
        Student student = new Student("林冲", 18);
        IndexRequest request = new IndexRequest("index_shz");
        // 配置核心属性
        request.id("6"); // id属性
        request.timeout("1s"); //设置超时时间
        // request.timeout(TimeValue.timeValueMillis(1)); //同上
        ObjectMapper objectMapper = new ObjectMapper();// jackson框架中的类
        //讲student对象转化一个json格式的字符串
        request.source(objectMapper.writeValueAsString(student), XContentType.JSON);
        //执行请求并返回结果
        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult()); //getResult，得到返回结果的信息，而不是具体数据
    }

    //5、判断文档是否存在
    @Test
    public void t5() throws IOException {
        //使用Get请求
        GetRequest request = new GetRequest("index_shz", "6");
        //配置不显示索引的上下文
        request.fetchSourceContext(new FetchSourceContext(false));
        request.storedFields("_none_");
        //获取文档信息
        boolean exists = esClient.exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    //6、查询文档内容
    @Test
    public void t6() throws IOException {
        //创建查询请求
        GetRequest request = new GetRequest("index_shz", "6");
        //执行查询请求，保存响应结果
        GetResponse response = esClient.get(request, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());
        System.out.println("-----------------------------");
        System.out.println(response);
    }

    //7、更新文档
    @Test
    public void t7() throws IOException {
        UpdateRequest request = new UpdateRequest("index_shz", "6");
        Student student = new Student("林教头", 32);
        ObjectMapper objectMapper = new ObjectMapper();
        //设置请求内容
        request.doc(objectMapper.writeValueAsString(student), XContentType.JSON);
        //执行更新方法
        UpdateResponse response = esClient.update(request, RequestOptions.DEFAULT);
        //输出响应结果
        System.out.println(response.getResult());
        System.out.println("---------------------");
        System.out.println(response);
    }

    //8、删除文档
    @Test
    public void t8() throws IOException {
        //创建一个删除文档的请求
        DeleteRequest request = new DeleteRequest("index_shz", "6");
        //执行删除请求， 保存响应结果
        DeleteResponse response = esClient.delete(request, RequestOptions.DEFAULT);
        //输出响应结果
        System.out.println(response);
    }

    //9、批量插入文档
    @Test
    public void t9() throws IOException{
        ArrayList list = new ArrayList();
        list.add(new Student("zhangsan",18));
        list.add(new Student("lisi",18));
        list.add(new Student("wangwu",18));
        list.add(new Student("kaungtu",18));
        list.add(new Student("guqinghan",18));
        // 创建一个支持批量操作的请求对象
        BulkRequest bulkRequest = new BulkRequest();
        ObjectMapper objectMapper = new ObjectMapper();
        for (int i = 0; i < list.size(); i++) {
            bulkRequest.add(new IndexRequest("index_shz")
                    .id(String.valueOf(i + 1))
                    .source(objectMapper.writeValueAsString(list.get(i)), XContentType.JSON));
        }
        BulkResponse response = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    //10、条件检索文档
    @Test
    public void t10() throws IOException {
        SearchRequest searchRequest = new SearchRequest("index_shz");
        //设置检索条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchQuery("name", "wangwu")); //分词检索，不是等值匹配
        searchRequest.source(builder);
        //执行条件检索，并保存结果
        SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(response);
        System.out.println("---------------");
        for (SearchHit hit : response.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }
}
